<template>
  <div v-if="visible" class="modal-overlay">
    <div class="header-content-top">
      <img class="header-icon" referrerpolicy="no-referrer" src="@/assets/img/module1/page1top2.png" />
      <span class="header-title">用户需求文件名{{ title }}</span>
    </div>
    <div class="dialog_main">
      <!-- 顶部的长方形区域，有背景图片和文字 -->
      <!-- <div class="header-section">
        <div class="header-content">
          <span class="header-text">用户需求文件名{{ title }}</span>
        </div>
        <button class="close-button-module1-yhr" @click="closeDialog"></button>
      </div> -->

      <!-- 下方占据剩余空间的部分，也有背景图片 -->
      <div class="body-section">
        <!-- subbody-1 顶部部分，居中显示 -->
        <div class="subbody-1">
          <div class="subbody-top">
            <div class="left-buttons">
              <button class="custom-button" @click="currentView = 'userInfo'">用户基本信息</button>
              <button class="custom-button" @click="currentView = 'airspaceDemand'">空域使用需求</button>
            </div>
            <el-button class="close-button-module1-yhr" type="primary" @click="closeDialog">返回列表</el-button>
          </div>

        </div>

        <!-- subbody-2 下方部分，内容展示 -->
        <div class="subbody-2">
          <div class="subbody-3">
            <!-- 用户基本信息 -->
            <div v-if="currentView === 'userInfo'" class="subbody-content">
              <div class="form-left">
                <div class="form-content">
                  <div class="form-item">
                    <label for="data1">申请单位</label>
                    <input id="data1" v-model="form.applicant" type="text" readonly />
                  </div>
                  <div class="form-item">
                    <label for="data2">联系人</label>
                    <input id="data2" v-model="form.contacts" type="text" readonly />
                  </div>
                  <div class="form-item">
                    <label for="data3">联系电话</label>
                    <input id="data3" v-model="form.telephone" type="text" readonly />
                  </div>
                  <div class="form-item">
                    <label for="data4">航空器厂商</label>
                    <input id="data4" v-model="form.aircraftManufacturer" type="text" readonly />
                  </div>
                  <div class="form-item">
                    <label for="data5">航空器型号</label>
                    <input id="data5" v-model="form.aircraftModel" type="text" readonly />
                  </div>
                </div>
              </div>
              <div class="form-right">
                <div class="form-content">
                  <div class="form-item">
                    <label for="data6">航空器类型</label>
                    <input id="data6" v-model="form.aircraftType" type="text" readonly />
                  </div>
                  <div class="form-item">
                    <label for="data7">航空器管制类型</label>
                    <input id="data7" v-model="form.aircraftControlType" type="text" readonly />
                  </div>
                  <div class="form-item">
                    <label for="data8">最大起飞重量</label>
                    <input id="data8" v-model="form.maximumTakeoffWeight" type="text" readonly />
                  </div>
                  <div class="form-item">
                    <label for="data9">航空器尺寸（展开）</label>
                    <input id="data9" v-model="form.dimensionsOfAircraftInDeployedState" type="text" readonly />
                  </div>
                </div>
              </div>
            </div>

            <!-- 空域使用需求 -->
            <div v-if="currentView === 'airspaceDemand'" class="airspace-demand-content">
              <!-- 表单部分 -->
              <div class="custom-form-content">
                <div class="custom-form-row">
                  <!-- <div class="custom-form-item">
                    <label for="airspaceUsageType">空域使用类型</label>
                    <input id="airspaceUsageType" v-model="form.airspaceUsageType" type="text" readonly/>
                  </div> -->
                  <div class="custom-form-item">
                    <label for="isReturn">是否往返</label>
                    <input id="isReturn" v-model="form.isRoundTrip" type="text" readonly />
                  </div>
                  <div class="custom-form-item">
                    <label for="flightTop">飞行顶高</label>
                    <input id="flightTop" v-model="form.maximumFlightAltitude" type="text" readonly />
                    <span class="custom-unit">米(m)</span>
                  </div>
                </div>
                <div class="custom-form-row">
                  <div class="custom-form-item">
                    <label for="taskType">任务类型</label>
                    <input id="taskType" v-model="form.taskType" type="text" readonly />
                  </div>
                  <div class="custom-form-item">
                    <label for="flightBottom">飞行底高</label>
                    <input id="flightBottom" v-model="form.minimumFlightAltitude" type="text" readonly />
                    <span class="custom-unit">米(m)</span>
                  </div>
                </div>

                <div class="custom-form-row">
                  <div class="custom-form-item">
                    <label for="taskStartTime">任务开始时间</label>
                    <input id="taskStartTime" v-model="form.taskStartTime" type="text" readonly />
                  </div>
                  <!-- <div class="custom-form-item">
                    <label for="isReturn">是否往返</label>
                    <input id="isReturn" v-model="form.isRoundTrip" type="text" readonly/>
                  </div> -->
                  <div class="custom-form-item">
                    <label for="flightFrequency">飞行频次</label>
                    <input id="flightFrequency" v-model="form.flightFrequency" type="text" readonly />
                    <span class="custom-unit"> 次/天</span>
                  </div>
                </div>

                <div class="custom-form-row">
                  <div class="custom-form-item">
                    <label for="taskEndTime">任务结束时间</label>
                    <input id="taskEndTime" v-model="form.taskEndTime" type="text" readonly />
                  </div>
                  <div class="custom-form-item">
                    <!-- <label for="flightFrequency">飞行频次</label>
                    <input id="flightFrequency" v-model="form.flightFrequency" type="text" readonly /> -->
                  </div>
                </div>

                <div class="custom-form-row">
                  <div class="custom-form-item full-width">
                    <label for="takeOffName">起飞机场</label>
                  </div>
                  <div class="custom-form-item-group">
                    <div class="custom-input-group">
                      <label for="takeOffName">名称</label>
                      <input id="takeOffName" v-model="form.takeoffLocationName" type="text" placeholder="名称" readonly
                        style="width: 100px;" />
                    </div>
                    <div class="custom-input-group">
                      <label for="takeOffNumber">编号</label>
                      <input id="takeOffNumber" v-model="form.takeoffLocationCode" type="text" placeholder="编号" readonly
                        style="width: 150px;" />
                    </div>
                    <div class="custom-input-group">
                      <label for="takeOffType">类型</label>
                      <input id="takeOffType" v-model="form.takeoffLocationType" type="text" placeholder="类型" readonly
                        style="width: 100px;" />
                    </div>
                    <div class="custom-input-group">
                      <label for="takeOffCoordinate">坐标</label>
                      <input id="takeOffCoordinate" v-model="form.takeoffLocationCoordinates" type="text"
                        placeholder="坐标" readonly />
                    </div>
                  </div>
                </div>

                <div class="custom-form-row">
                  <div class="custom-form-item full-width">
                    <label for="landingName">降落机场</label>
                  </div>
                  <div class="custom-form-item-group">
                    <div class="custom-input-group">
                      <label for="landingName">名称</label>
                      <input id="landingName" v-model="form.landingLocationName" type="text" placeholder="名称" readonly
                        style="width: 100px;" />
                    </div>
                    <div class="custom-input-group">
                      <label for="landingNumber">编号</label>
                      <input id="landingNumber" v-model="form.landingLocationCode" type="text" placeholder="编号" readonly
                        style="width: 150px;" />
                    </div>
                    <div class="custom-input-group">
                      <label for="landingType">类型</label>
                      <input id="landingType" v-model="form.landingLocationType" type="text" placeholder="类型" readonly
                        style="width: 100px;" />
                    </div>
                    <div class="custom-input-group">
                      <label for="landingCoordinate">坐标</label>
                      <input id="landingCoordinate" v-model="form.landingLocationCoordinates" type="text"
                        placeholder="坐标" readonly />
                    </div>
                  </div>
                </div>


                <!-- <div class="info-box-yhr-dialog-module1">
                  空域类型：
                  <span v-if="form.airspaceType === 0">圆形</span>
                  <span v-else-if="form.airspaceType === 1">多边形</span>
                  <span v-else-if="form.airspaceType === 2">线形</span>
                  <span v-else>未知类型</span>
                </div> -->

                <div class="regional_table">
                  <!-- 判断圆形轨迹是否存在 -->
                  <template v-if="form.circularAirspace === 1">
                    <h3>圆形柱体轨迹</h3>
                    <el-table :data="tableData.circular" style="width: 100%" max-height="450">
                      <el-table-column label="圆心经度" width="150">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('circular', scope.row)">
                            {{ formatCoordinate(scope.row.longitude) }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column label="圆心纬度" width="150">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('circular', scope.row)">
                            {{ formatCoordinate(scope.row.latitude) }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column label="最小高度" width="150">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('circular', scope.row)">
                            {{ scope.row.minAltitude }} 米
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column label="最大高度" width="150">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('circular', scope.row)">
                            {{ scope.row.maxAltitude }} 米
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column label="半径" width="150">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('circular', scope.row)">
                            {{ scope.row.radius }} 米
                          </span>
                        </template>
                      </el-table-column>
                    </el-table>
                  </template>

                  <!-- 判断多边形轨迹是否存在 -->
                  <template v-if="form.polygonalAirspace === 1">
                    <h3>多边形柱体轨迹</h3>
                    <el-table :data="tableData.polygonal" style="width: 100%" max-height="450">
                      <el-table-column label="轨迹编号" width="150">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('polygonal', scope.row)">
                            轨迹 {{ scope.row.wayId }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column label="多边形轨迹点集合" width="500">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('polygonal', scope.row)">
                            {{ scope.row.pointNames.join(', ') }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column label="最小高度" width="150">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('polygonal', scope.row)">
                            {{ scope.row.minAltitude }} 米
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column label="最大高度" width="150">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('polygonal', scope.row)">
                            {{ scope.row.maxAltitude }} 米
                          </span>
                        </template>
                      </el-table-column>
                    </el-table>
                  </template>

                  <!-- 判断线形轨迹是否存在 -->
                  <template v-if="form.straightAirspace === 1">
                    <h3>线形柱体轨迹</h3>
                    <el-table :data="tableData.straight" style="width: 100%" max-height="450">
                      <el-table-column label="轨迹编号" width="150">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('straight', scope.row)">
                            轨迹 {{ scope.row.wayId }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column label="线形航迹轨迹点">
                        <template #default="scope">
                          <span @click="focusOnTrajectory('straight', scope.row)">
                            {{ scope.row.urlStrings.join(', ') }}
                          </span>
                        </template>
                      </el-table-column>
                    </el-table>
                  </template>

                  <!-- 没有数据的情况 -->
                  <template
                    v-if="form.circularAirspace !== 1 && form.polygonalAirspace !== 1 && form.straightAirspace !== 1">
                    <p>没有空域轨迹数据</p>
                  </template>
                </div>
              </div>

              <!-- GIS展示部分 -->
              <div class="image-content">
                <div id="cesiumContainer-module1-yhr"></div>
              </div>
            </div>

            <div class="module1-yhr-button-container">
              <button class="module1-yhr-custom-btn" @click="submitForm(2)">驳回</button>
              <button class="module1-yhr-custom-btn" @click="submitForm(1)">接收</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { nextTick } from 'vue';
import { drawCircleArea, drawParallelogramArea, drawSquareArea } from '@/utils/draw2DShapes.js';
import { drawCylinderArea } from '@/utils/draw3DShapes.js';
import { drawCylinderAreaM1, draw3DRectangularPipelineTrackM1, draw3DPolygonalPrismM1, draw3DRectangularPipelineTrackM1_2 } from '@/utils/draw3D-module1.js';
import { draw3DPipelineTrack, draw3DRectangularPipelineTrack } from '@/utils/drawPipeline.js';
import { drawLine } from '@/utils/drawPath.js';

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    title: {
      type: String,
      default: "默认标题"
    },
    dialogData: {
      type: Object,
      required: true
    },
  },
  data() {
    return {
      currentView: 'userInfo', // 默认显示用户基本信息
      form: {
        // 用户信息
        applicant: '', // 申请单位
        contacts: '',  // 联系人
        telephone: '', // 联系电话
        aircraftManufacturer: '', // 航空器厂商
        aircraftModel: '', // 航空器型号
        aircraftType: '', // 航空器类型
        aircraftControlType: '', // 航空器管制类型
        maximumTakeoffWeight: '', // 最大起飞重量
        dimensionsOfAircraftInDeployedState: '', // 航空器尺寸（展开）
        // 空域使用需求
        airspaceUsageType: '',          // 空域使用类型
        maximumFlightAltitude: '',      // 飞行项高
        taskType: '',                   // 任务类型
        minimumFlightAltitude: '',      // 飞行底高
        taskStartTime: '',              // 任务开始时间
        isRoundTrip: '',                // 是否往返
        taskEndTime: '',                // 任务结束时间
        flightFrequency: '',            // 飞行频次
        takeoffLocationName: '',        // 起降机场（起飞）的名称
        takeoffLocationCode: '',        // 起飞机场编号
        takeoffLocationType: '',        // 起飞机场类型
        takeoffLocationCoordinates: '', // 起飞机场坐标
        landingLocationName: '',        // 起降机场（降落）的名称
        landingLocationCode: '',        // 降落机场编号
        landingLocationType: '',        // 降落机场类型
        landingLocationCoordinates: ''  // 降落机场坐标
      },
      tableData: [],
      viewer: null,
    };
  },
  mounted() {
    console.log('dialogData:', this.dialogData); // 在组件加载时打印dialogData
  },
  watch: {
    title: {
      immediate: true,
      handler(newVal) {
        console.log('title changed:', newVal);
        if (newVal) {
          this.fetchData(newVal);  // 调用fetchData，传入id
        }
      }
    },
    currentView(newValue) {
      // 监听 currentView 变化，判断是否为 'airspaceDemand'
      console.log("currentView变化了，变为了", newValue)
      if (newValue === 'airspaceDemand') {
        // 确保 DOM 渲染完成后再初始化 Cesium
        // 确保 DOM 渲染完成后再初始化 Cesium
        nextTick().then(async () => {
          await this.initializeCesium();  // 确保 Cesium 初始化完成
          await this.DrawTrajectory();    // 然后再绘制航迹
        }).catch(error => {
          console.error('Cesium初始化时发生错误:', error);
        });
      } else {
        this.destroyCesium();
      }
    },
  },
  methods: {
    async initializeCesium() {
      try {
        this.viewer = new Cesium.Viewer('cesiumContainer-module1-yhr', {
          sceneModePicker: false,
          baseLayerPicker: false,
          geocoder: false,
          homeButton: false,
          navigationHelpButton: false,
          infoBox: false,
          timeline: false, // 移除时间轴
          animation: false // 移除动画控件
        });
        this.viewer.scene.frameState.creditDisplay.container.style.display = 'none';

        console.log("viewer", this.viewer)

        this.viewer.camera.setView({
          destination: Cesium.Cartesian3.fromDegrees(113.5, 22.1, 1000)
        });
        console.log("cesium初始化成功")
      } catch (error) {
        console.error('Cesium initialization failed:', error);
      }
    },
    async DrawTrajectory() {
      try {
        const { circular, polygonal, straight } = this.tableData;
        const entitiesToFlyTo = [];
        // 存储当前的经纬度标签实体
        let currentLabelEntity = null;

        console.log("this.form.takeoffLocationCoordinates", this.form.takeoffLocationCoordinates)
        console.log("this.form.landingLocationCoordinates", this.form.landingLocationCoordinates)
        // 转换起飞和降落机场的坐标，并绘制圆柱体
        if (this.form.takeoffLocationCoordinates) {
          const [takeoffLon, takeoffLat] = this.parseCoordinates(this.form.takeoffLocationCoordinates);
          const takeoffEntity = drawCylinderAreaM1(
            this.viewer,
            takeoffLon,
            takeoffLat,
            0,
            50,
            50,
            'RED',
            0.5
          );
          entitiesToFlyTo.push(takeoffEntity);

          // 添加起飞机场标签
          this.viewer.entities.add({
            position: Cesium.Cartesian3.fromDegrees(takeoffLon, takeoffLat, 60), // 提高标签的高度
            label: {
              text: '起飞机场',
              font: '10pt monospace',
              fillColor: Cesium.Color.RED,
              style: Cesium.LabelStyle.FILL_AND_OUTLINE,
              outlineWidth: 2,
              outlineColor: Cesium.Color.BLACK,
              verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
              heightReference: Cesium.HeightReference.NONE,
              disableDepthTestDistance: Number.POSITIVE_INFINITY,
            }
          });

          // 点击事件移动到起飞机场
          document.getElementById('takeOffCoordinate').addEventListener('click', () => {
            this.viewer.flyTo(takeoffEntity, {
              duration: 2,
              offset: {
                heading: Cesium.Math.toRadians(0),
                pitch: Cesium.Math.toRadians(-45),
                roll: 0
              }
            });
          });
        }

        if (this.form.landingLocationCoordinates) {
          const [landingLon, landingLat] = this.parseCoordinates(this.form.landingLocationCoordinates);
          const landingEntity = drawCylinderAreaM1(
            this.viewer,
            landingLon,
            landingLat,
            0,
            50,
            50,
            'BLUE',
            0.5
          );
          entitiesToFlyTo.push(landingEntity);

          // 添加降落机场标签
          this.viewer.entities.add({
            position: Cesium.Cartesian3.fromDegrees(landingLon, landingLat, 60), // 提高标签的高度
            label: {
              text: '降落机场',
              font: '10pt monospace',
              fillColor: Cesium.Color.BLUE,
              style: Cesium.LabelStyle.FILL_AND_OUTLINE,
              outlineWidth: 2,
              outlineColor: Cesium.Color.BLACK,
              verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
              heightReference: Cesium.HeightReference.NONE,
              disableDepthTestDistance: Number.POSITIVE_INFINITY,
            }
          });

          // 点击事件移动到降落机场
          document.getElementById('landingCoordinate').addEventListener('click', () => {
            this.viewer.flyTo(landingEntity, {
              duration: 2,
              offset: {
                heading: Cesium.Math.toRadians(0),
                pitch: Cesium.Math.toRadians(-45),
                roll: 0
              }
            });
          });
        }
        // 绘制圆柱体轨迹（如果有的话）
        if (circular.length > 0) {
          circular.forEach((coord, index) => {
            const entity = drawCylinderAreaM1(
              this.viewer,
              coord.longitude,
              coord.latitude,
              coord.minAltitude,
              coord.maxAltitude,
              coord.radius,
              'GREEN',
              0.5
            );
            if (entity) {
              this.tableData.circular[index].entity = entity;
              entitiesToFlyTo.push(entity);
            }
          });
        }

        // 绘制多边形柱状体轨迹
        if (polygonal.length > 0) {
          console.log("绘制多边形柱状体传入的数据", polygonal)
          polygonal.forEach((track, index) => {
            const entity = draw3DPolygonalPrismM1(
              this.viewer,
              track.coordinates.map(coord => [coord.longitude, coord.latitude]).flat(),
              track.minAltitude,
              track.maxAltitude,
              'BLUE',
              0.5,
              track.pointNames  // 传递点名
            );
            if (entity) {
              this.tableData.polygonal[index].entity = entity;
              entitiesToFlyTo.push(entity);
            }
          });
        }

        // 绘制长方体管道轨迹（如果有的话）
        if (straight.length > 0) {
          console.log("绘制长方体管道传入的数据", straight);
          straight.forEach((track, index) => {
            const coordinates = track.coordinates.map(coord => [coord.longitude, coord.latitude, coord.altitude]).flat();
            const pointNames = track.urlStrings; // 获取每个轨迹点的名字

            // Ensure sizes array has the correct length
            const sizes = new Array(coordinates.length / 3 - 1).fill([100, 50]); // 对应生成每段长宽

            // Check if sizes length matches coordinates length - 1
            if (sizes.length !== coordinates.length / 3 - 1) {
              console.error('Sizes array length does not match coordinates array length minus one');
            } else {
              const entities = draw3DRectangularPipelineTrackM1_2(
                this.viewer,
                coordinates,
                sizes,
                'YELLOW',
                pointNames // 传递轨迹点名字数组
              );
              if (entities) {
                this.tableData.straight[index].entity = entities;
                entitiesToFlyTo.push(...entities);
              }
            }
          });
        }

        // 如果有实体被绘制，飞行到这些实体的视角
        if (entitiesToFlyTo.length > 0) {
          this.viewer.flyTo(entitiesToFlyTo, {
            duration: 2,
            offset: {
              heading: Cesium.Math.toRadians(0),
              pitch: Cesium.Math.toRadians(-30),  // 视角抬高一些
              roll: 0
            }
          });
        }



        // 启用点击事件，显示经纬度和高度信息
        this.viewer.screenSpaceEventHandler.setInputAction((movement) => {
          // 清除之前的标签实体
          if (currentLabelEntity) {
            this.viewer.entities.remove(currentLabelEntity);
            currentLabelEntity = null;
          }

          const pickedObject = this.viewer.scene.pick(movement.position);

          // 如果点击了有效对象，显示经纬度和高度信息
          if (pickedObject && pickedObject.id && pickedObject.id.position) {
            const position = pickedObject.id.position.getValue(Cesium.JulianDate.now());
            if (position) {
              const cartographic = Cesium.Ellipsoid.WGS84.cartesianToCartographic(position);
              const longitude = Cesium.Math.toDegrees(cartographic.longitude).toFixed(6);
              const latitude = Cesium.Math.toDegrees(cartographic.latitude).toFixed(6);
              const height = cartographic.height.toFixed(2);

              // 创建显示坐标的标签
              currentLabelEntity = this.viewer.entities.add({
                position: position,
                label: {
                  text: `Lon: ${longitude}\nLat: ${latitude}\nHeight: ${height} m`,
                  font: '14pt monospace',
                  fillColor: Cesium.Color.YELLOW,
                  style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                  outlineWidth: 2,
                  outlineColor: Cesium.Color.BLACK,
                  verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                  heightReference: Cesium.HeightReference.NONE,
                  disableDepthTestDistance: Number.POSITIVE_INFINITY,
                }
              });
            }
          }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      } catch (error) {
        console.error('绘制航迹时发生错误:', error);
      }
    },
    dmsToDecimal(dms) {
      const [degrees, minutes, seconds] = dms.split(/[^\d\w.]+/).map(Number);
      return degrees + (minutes / 60) + (seconds / 3600);
    },

    parseCoordinates(coordString) {
      const [lonDMS, latDMS] = coordString.split(',').map(s => s.trim());
      const lon = this.dmsToDecimal(lonDMS);
      const lat = this.dmsToDecimal(latDMS);
      return [lon, lat];
    },
    focusOnTrajectory(type, row) {
      const entity = row.entity;

      if (entity && this.viewer) {
        this.viewer.flyTo(entity, {
          duration: 2,
          offset: {
            heading: Cesium.Math.toRadians(0),
            pitch: Cesium.Math.toRadians(-45),
            roll: 0
          }
        });
      }
    },
    destroyCesium() {
      // 在切换离开 'airspaceDemand' 时销毁 Cesium 实例
      if (this.viewer) {
        this.viewer.destroy();
        this.viewer = null;
      }
    },
    // 初始化时向后端发送请求，获取数据
    async fetchData(title) {
      try {
        // // 确保 id 是一个整数
        // const numericId = parseInt(id, 10);  // 将 id 转为整型
        // if (isNaN(numericId)) {
        //   throw new Error('ID 不是一个有效的整型');
        // }
        // const response = await axios.post('/api/module1/userDetail_yhr', { id });
        // const response = await axios.post('http://127.0.0.1:4523/m2/5137922-4801689-default/214473170', { title });
        // // 使用 POST 请求并将 id 作为查询参数附加到 URL
        console.log("给后端发送的文件名信息", title)
        const stringTitle = title.toString()
        console.log("给后端发送的文件名string信息", stringTitle)
        const response = await axios.post(`http://47.99.75.194:8081/admin/airspaceDemand/getById`, null, {
          params: {
            applicationId: stringTitle
          }
        });


        // 打印从接口获取的数据
        console.log('接口返回的数据:', response.data);

        // 将接口返回的数据一一对应赋值给form
        this.form = {
          applicant: response.data.data.applicant,
          contacts: response.data.data.contacts,
          telephone: response.data.data.telephone,
          aircraftManufacturer: response.data.data.aircraftManufacturer,
          aircraftModel: response.data.data.aircraftModel,
          aircraftType: response.data.data.aircraftType,
          aircraftControlType: response.data.data.aircraftControlType,
          maximumTakeoffWeight: response.data.data.maximumTakeoffWeight,
          dimensionsOfAircraftInDeployedState: response.data.data.dimensionsOfAircraftInDeployedState,
          maximumFlightAltitude: response.data.data.maximumFlightAltitude,
          taskType: response.data.data.taskType,
          minimumFlightAltitude: response.data.data.minimumFlightAltitude,
          taskStartTime: this.formatTaskStartTime(response.data.data.taskStartTime),
          isRoundTrip: response.data.data.isRoundTrip,
          taskEndTime: this.formatTaskStartTime(response.data.data.taskEndTime),
          flightFrequency: response.data.data.flightFrequency,
          takeoffLocationName: response.data.data.takeoffLocationName,
          takeoffLocationCode: response.data.data.takeoffLocationCode,
          takeoffLocationType: response.data.data.takeoffLocationType,
          takeoffLocationCoordinates: `${this.formatCoordinate(response.data.data.takeoffLocationCoordinates.longitude)}, ${this.formatCoordinate(response.data.data.takeoffLocationCoordinates.latitude)}`,
          landingLocationName: response.data.data.landingLocationName,
          landingLocationCode: response.data.data.landingLocationCode,
          landingLocationType: response.data.data.landingLocationType,
          landingLocationCoordinates: `${this.formatCoordinate(response.data.data.landingLocationCoordinates.longitude)}, ${this.formatCoordinate(response.data.data.landingLocationCoordinates.latitude)}`,
          id: response.data.data.id,
          userName: response.data.data.userName,
          applicationAcceptanceTime: response.data.data.applicationAcceptanceTime,
          applicationId: response.data.data.applicationId,
          approvalStatus: response.data.data.approvalStatus,
          airspaceType: response.data.data.airspaceType,
          circularAirspace: response.data.data.circularAirspace,
          polygonalAirspace: response.data.data.polygonalAirspace,
          straightAirspace: response.data.data.straightAirspace,
          circleCenterCoordinates: `${response.data.data.circleCenterCoordinates.longitude}, ${response.data.data.circleCenterCoordinates.latitude}`,
          radius: response.data.data.radius,
        };


        // 处理 tableData
        this.tableData = {
          circular: [],
          polygonal: [],
          straight: []
        };

        // 如果圆形轨迹存在，添加相应的数据
        if (response.data.data.circleCenterCoordinates && response.data.data.circleCenterCoordinates.length > 0) {
          this.tableData.circular = response.data.data.circleCenterCoordinates.map(coord => ({
            longitude: coord.longitude,
            latitude: coord.latitude,
            minAltitude: coord.minAltitude,
            maxAltitude: coord.maxAltitude,
            radius: coord.radius,
            pointName: `Circle Center`  // 为圆心命名
          }));
        }

        // 如果多边形轨迹存在，按 wayId 进行分类
        if (response.data.data.polygonalWaypointsCoordinates && response.data.data.polygonalWaypointsCoordinates.length > 0) {
          const groupedPolygonal = {};

          response.data.data.polygonalWaypointsCoordinates.forEach(point => {
            const wayId = point.wayId;
            if (!groupedPolygonal[wayId]) {
              groupedPolygonal[wayId] = {
                pointNames: [],
                minAltitude: point.minAltitude,
                maxAltitude: point.maxAltitude,
                coordinates: []
              };
            }
            const pointName = `URZ${wayId}-${point.pointId}`;
            groupedPolygonal[wayId].pointNames.push(pointName);

            groupedPolygonal[wayId].coordinates.push({
              longitude: point.longitude,
              latitude: point.latitude
            });
          });

          this.tableData.polygonal = Object.keys(groupedPolygonal).map(wayId => ({
            wayId: wayId,
            pointNames: groupedPolygonal[wayId].pointNames,
            minAltitude: groupedPolygonal[wayId].minAltitude,
            maxAltitude: groupedPolygonal[wayId].maxAltitude,
            coordinates: groupedPolygonal[wayId].coordinates
          }));
        }

        // 如果线形轨迹存在，按 wayId 进行分类
        if (response.data.data.straightWaypointsCoordinates && response.data.data.straightWaypointsCoordinates.length > 0) {
          const groupedStraight = {};

          response.data.data.straightWaypointsCoordinates.forEach(point => {
            const wayId = point.wayId;
            if (!groupedStraight[wayId]) {
              groupedStraight[wayId] = {
                urlStrings: [],
                coordinates: []
              };
            }
            const urlString = `URL${wayId}-${point.pointId}`;
            groupedStraight[wayId].urlStrings.push(urlString);

            groupedStraight[wayId].coordinates.push({
              longitude: point.longitude,
              latitude: point.latitude,
              altitude: point.altitude
            });
          });

          this.tableData.straight = Object.keys(groupedStraight).map(wayId => ({
            wayId: wayId,
            urlStrings: groupedStraight[wayId].urlStrings,
            coordinates: groupedStraight[wayId].coordinates
          }));
        }

        console.log("更新后的form", this.form);
        console.log("更新后的tableData", this.tableData);
      } catch (error) {
        console.error('请求接口时发生错误:', error);
      }
    },
    // 根据 airspaceType 动态返回 positionList
    getPositionList(data) {
      if (data.airspaceType === 0) {
        // 如果是 0，使用 circleCenterCoordinates（圆形轨迹），只展示一个点
        return [{
          longitude: data.circleCenterCoordinates.longitude,
          latitude: data.circleCenterCoordinates.latitude,
          altitude: data.circleCenterCoordinates.altitude,
          radius: data.radius
        }];
      } else if (data.airspaceType === 1 || data.airspaceType === 2) {
        // 如果是 1 或 2，展示 waypointsCoordinates
        return data.waypointsCoordinates.map(point => ({
          longitude: point.longitude,
          latitude: point.latitude,
          altitude: point.altitude
        }));
      } else {
        // 如果没有匹配，返回空数组或其他默认值
        return [];
      }
    },
    // 转换经度、纬度的格式，转换成度分秒的形式
    formatCoordinate(coord) {
      const degrees = Math.floor(coord);
      const minutes = Math.floor((coord - degrees) * 60);
      const seconds = (((coord - degrees) * 60 - minutes) * 60).toFixed(1);
      return `${degrees}°${minutes}'${seconds}"`;
    },
    // 格式化任务开始时间，将异常格式转换为有效日期格式
    formatTaskStartTime(timeStr) {
      // 确保 timeStr 是一个有效的时间字符串
      const date = new Date(timeStr);
      console.log("拿到的时间数据初始版本", timeStr)
      // 检查是否是一个有效日期
      if (isNaN(date.getTime())) {
        return '';  // 如果日期无效，返回空字符串
      }

      // 格式化日期为 yyyy-MM-dd HH:mm:ss 格式
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');  // 补全为两位数
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    closeDialog() {
      this.$emit('update:visible', false);
    },
    // 提交表单的函数
    async submitForm(newApprovalStatus) {
      try {
        const id = this.form.id;  // 从表单中获取订单需求的 id
        const title = this.title
        console.log("文件名", title)
        const response = await axios.post('http://47.99.75.194:8081/admin/airspaceDemand/updateApprovalStatus', {
          applicationId: title,  // 订单需求的 id
          newApprovalStatus: newApprovalStatus  // 根据点击的按钮设置状态，同意为1，驳回为2
        });

        console.log('同意/驳回请求返回的数据:', response.data);
        if (response.data.code == 0) {
          this.$emit('update:visible', false);  // 成功后关闭弹窗
          this.$message.success('操作成功');
          this.$emit('status-updated'); // 通知父组件状态已更新
        } else {
          this.$message.error('操作失败');
        }
      } catch (error) {
        console.error('请求时发生错误:', error);
        this.$message.error('请求失败，请稍后再试');
      }
    },
  }
};
</script>

<style scoped>
.header-content-top {
  position: relative;
  width: 100%;
  /* 使其占据整个宽度 */
  height: 5%;
  background: url("@/assets/img/module1/page1top.png") no-repeat;
  background-size: cover;
  display: flex;
  align-items: center;
  /* 垂直居中 */
  /* 增加内部间距 */
}

/* 标题样式 */
.header-title {
  background-image: linear-gradient(180deg,
      rgba(200, 215, 228, 1) 0,
      rgba(255, 255, 255, 1) 100%);
  position: relative;
  font-weight: 600;
  flex: 2;
  margin-left: 40px;
  width: 10%;
  height: 10%;
  color: rgba(112, 112, 112, 1);
  font-size: 20px;
  letter-spacing: 1px;
  font-family: PangMenZhengDao-3;
  text-align: left;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* 图标样式 */
.header-icon {
  position: relative;
  width: 22px;
  height: 20px;
  margin-left: 20px;
  /* 与其他内容间隔 */
  margin-top: -20px;
}

.dialog_main {
  width: 100%;
  height: 81.5vh;
  border-radius: 10px;
  padding: 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
  background-color: transparent;
}

.header-section {
  width: 100%;
  height: 5%;
  background: url('@/assets/img/module1/dialog_top.png') no-repeat center center;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
}

.header-content {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.header-text {
  color: white;
  font-size: 1.2rem;
  font-weight: bold;
  text-align: center;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
}

.body-section {
  flex-grow: 1;
  background: url('@/assets/img/module1/dialog_bg.png') no-repeat center center;
  background-size: cover;
  padding: 2rem 3rem 0.9rem 3rem;
  display: flex;
  flex-direction: column;
}

.subbody-1 {
  width: 100%;
  background: url('@/assets/img/module1/dialog_bg2.png') no-repeat center center;
  background-size: cover;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-direction: column;
}

.subbody-top {
  width: 100%;
  display: flex;
  justify-content: space-between;
  /* 左右两端对齐 */
  align-items: center;
  margin-bottom: 1rem;
}

.left-buttons {
  display: flex;
  gap: 0.1rem;
  /* 按钮之间的间距 */
}

.custom-button {
  width: 15rem;
  height: 5rem;
  background: url('@/assets/img/module1/dialog_button_unchosen.png') no-repeat center center;
  background-size: contain;
  border: none;
  color: white;
  font-weight: bold;
  cursor: pointer;
}

.custom-button:hover {
  opacity: 0.8;
  background: url('@/assets/img/module1/dialog_button_chosen.png') no-repeat center center;
  background-size: contain;
}

.close-button-module1-yhr {
  width: auto;
  height: auto;
  margin-right: 1rem;
  /* 适当调整按钮大小 */
  border: none;
  color: #fff;
  cursor: pointer;
}

.subbody-3 {
  width: 95%;
}

.subbody-2 {
  width: 100%;
  height: 80%;
  background: url('@/assets/img/module1/dialog_bg2.png') no-repeat center center;
  background-size: cover;
  display: flex;
}

/* 左侧和右侧的样式 */
.subbody-content {
  height: 35vh;
  display: flex;
  justify-content: space-between;
  padding: 8vh 5vw 0 5vw;
  overflow: auto;
}

.form-left,
.form-right {
  width: 45%;
}

.form-content {
  display: flex;
  flex-direction: column;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 0.5rem;
}

label {
  width: 10vw;
  /* font-weight: bold; */
  text-align: right;
  margin-right: 1vw;
}

input {
  flex: 1;
  padding: 8px;
  box-sizing: border-box;
  border: 1px solid #cccccc18;
  border-radius: 4px;
  background-color: #cccccc18;
  color: gray;
}

/* 空域使用需求部分 */
.airspace-demand-content {
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 52vh;
  overflow-y: auto;
  /* 超出时垂直滚动 */
}

/* 隐藏滚动条 - Webkit浏览器（Chrome, Safari等） */
.airspace-demand-content::-webkit-scrollbar {
  width: 0;
  height: 0;
}

/* 隐藏滚动条 - Firefox */
.airspace-demand-content {
  scrollbar-width: none;
  /* Firefox 隐藏滚动条 */
}

/* 隐藏滚动条 - IE/Edge */
.airspace-demand-content {
  -ms-overflow-style: none;
  /* IE/Edge 隐藏滚动条 */
}

.image-content {
  width: 30%;
  height: 30rem;
  /* background-color: rgba(127, 255, 212, 0.141); */
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 自定义表单内容 */
.custom-form-content {
  width: 65%;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.custom-form-row {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

.custom-form-item {
  display: flex;
  align-items: center;
  flex: 1;
}

.custom-form-item.full-width {
  width: 100%;
}

.custom-form-item label {
  width: 8vw;
  color: white;
  font-size: small;
  text-align: right;
  margin-right: 10px;
}

.custom-form-item input {
  flex: 1;
  padding: 6px 12px;
  width: 25%;
  background-color: transparent;
  border: 1px solid #ccc;
  border-radius: 4px;
  color: #ccc;
}

.custom-form-item-group {
  display: flex;
  gap: 0.5rem;
}

.custom-unit {
  margin-left: 5px;
  color: white;
}

/* 空域类型提示框 */
.info-box-yhr-dialog-module1 {
  background-color: #2d2d2df1;
  color: white;
  border-radius: 4px;
  font-size: 1rem;
  width: 30%;
  margin-left: 1rem;
}

.regional_table {
  margin-left: 1rem;
  height: 13vh;
}

/* 最外层透明表格背景与白色字体 */
.regional_table /deep/ .el-table,
.regional_table /deep/ .el-table__expanded-cell {
  background-color: transparent;
  /* 设置透明背景 */
  color: white;
  /* 表格文字颜色 */
}

/* 表格头部和单元格的背景颜色透明 */
.regional_table /deep/ .el-table th,
.regional_table /deep/ .el-table tr,
.regional_table /deep/ .el-table td {
  background-color: transparent !important;
  /* 背景透明 */
  color: white;
  /* 确保文字为白色 */
}

/* 设置表格边框 */
.regional_table /deep/ .el-table__body-wrapper {
  /* border: 1px solid white;  */
}


.regional_table /deep/ .el-table .el-table__cell {
  padding: 0;
}

/* 如果表头或其他部分需要特殊透明处理 */
.regional_table /deep/ .el-table__header-wrapper {
  background-color: rgba(255, 255, 255, 0.1);
  /* 表头轻微透明 */
}



/* 按钮样式 */
.module1-yhr-button-container {
  display: flex;
  justify-content: center;
}

.module1-yhr-custom-btn {
  width: 10%;
  height: 2rem;
  background-size: cover;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  background-color: transparent;
  color: #fff;
  margin: 0 1rem;
}

/* 提交按钮背景图片 */
.module1-yhr-custom-btn:first-child {
  background-image: url('@/assets/img/module1/button-bohui.png');
}

/* 重置按钮背景图片 */
.module1-yhr-custom-btn:last-child {
  background-image: url('@/assets/img/module1/button-tijiao.png');
}

/* 鼠标悬停效果 */
.module1-yhr-custom-btn:hover {
  opacity: 0.8;
}


#cesiumContainer-module1-yhr {
  width: 100%;
  height: 100%;
  position: relative;
}
</style>
